package common.utils;

import com.alibaba.fastjson.util.IOUtils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class BinaryUtil {
//    //报错
//    public static String GetText(InputStream stream) throws Exception {
//        DataInputStream dataReader = new DataInputStream(stream);
//        String result = dataReader.readUTF();
//        dataReader.close();
//        stream.close();
//        return result;
//    }

    public static String getText(InputStream stream, Charset charset) throws Exception {
        InputStreamReader dataReader = new InputStreamReader(stream, charset);
        String result = IOUtils.readAll(dataReader);
        dataReader.close();
        stream.close();
        return result;
    }

    public static String getText(InputStream stream) throws Exception {
        return getText(stream, CharsetUtil.Utf8);
    }

    public static void WriteText(OutputStream stream, String data, Charset charset) throws Exception {
        ByteBuffer buffer = charset.encode(data);
        stream.write(buffer.array());
        stream.close();
    }


/*    //有问题 长度不对
    public static byte[] GetFromText(String text) {
        ByteBuffer buffer = CharsetUtil.Utf8.encode(text);
        byte[] bytes = buffer.array();
        return bytes;
    }*/

    public static byte[] GetFromText(String text) {
        return text.getBytes(CharsetUtil.Utf8);
    }

    public static ByteBuffer GetBufferFromText(String text) {
        return CharsetUtil.Utf8.encode(text);
    }
}
